package com.atguigu.gulimail.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.atguigu.gulimail.product.dao.CategoryBrandRelationDao;
import com.atguigu.gulimail.product.entity.CategoryBrandRelationEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.BrandDao;
import com.atguigu.gulimail.product.entity.BrandEntity;
import com.atguigu.gulimail.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        final IPage<BrandEntity> page1 = new Query<BrandEntity>().getPage(params);
        final QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (params.containsKey("key")) {
            final String key = (String) params.get("key");
            wrapper.like("name", key).or().eq("brand_id", key);
        }

        IPage<BrandEntity> page = this.page(
                page1,
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void update(BrandEntity brand) {

        final BrandEntity byId = getById(brand.getBrandId());

        this.updateById(brand);
        if (StringUtils.isNotEmpty(brand.getName()) && !byId.getName().equals(brand.getName())) {
//            CategoryBrandRelationEntity categoryBrandRelationEntity =
//                    new CategoryBrandRelationEntity();
//            categoryBrandRelationEntity.setBrandId(brand.getBrandId());
//            categoryBrandRelationEntity.setBrandName(brand.getName());
//            UpdateWrapper<CategoryBrandRelationEntity> wrapper =
//                    new UpdateWrapper<>();
//            wrapper.eq("brand_id", brand.getBrandId())
//                    .set("brand_name", brand.getName());
            categoryBrandRelationDao.updateBrand(brand.getBrandId(),
                    brand.getName());
        }
    }


    @Transactional
    @Override
    public void removeBrands(Long[] brandIds) {
        removeByIds(Arrays.asList(brandIds));
        categoryBrandRelationDao.delete(new QueryWrapper<CategoryBrandRelationEntity>()
                .in("brand_id", brandIds));
    }
}